home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12616 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why does my program do this?
  5. Date: Mon, 01 Apr 96 23:01:48 GMT
  6. Organization: none
  7. Message-ID: <828399708snz@genesis.demon.co.uk>
  8. References: <4jnln2$95j@dfw-ixnews3.ix.netcom.com> <4jpe4s$db2@penage.cs.laurentian.ca>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: relay-4.mail.demon.net!post.demon.co.uk!genesis.demon.co.uk
  13.  
  14. In article <4jpe4s$db2@penage.cs.laurentian.ca>
  15.            ecchan@calum.uwaterloo.ca "Edward C. Chan" writes:
  16.  
  17. >>char scores[STUDENT][5];
  18. >>
  19. >>    for (i=0; i <= students-1; i=i+1)
  20. >>        {
  21. >>            for (j=0; j <= tests-1; j=j+1)
  22. >>            {
  23. >>                gets(&scores[i][j]);
  24. >>            }
  25. >>        }
  26. >>
  27.  
  28. The problem is that gets() takes a pointer to the first character of an
  29. array of char and writes a string to it. Therefore subsequent gets()
  30. calls are overwriting the data read by earlier ones. You need an array of
  31. char to hold each score. Also never use gets() since you can't prevent it
  32. overwriting the end of the buffer if the input data line is too long.
  33.  
  34. >user error.
  35. >
  36. >replace 
  37. >
  38. >   gets(&scores[i][j]);
  39. >
  40. >with
  41. >
  42. >   gets(scores[i][j]);
  43.  
  44. scores[i][j] is a char and gets() requires a char * argument so this is
  45. plainly wrong, it probably won't even compile (if you include stdio.h).
  46.  
  47. >andeverything shall work fine.  Actually, you are lucky that the programme
  48. >doesn't crash on you.
  49.  
  50. -- 
  51. -----------------------------------------
  52. Lawrence Kirby | fred@genesis.demon.co.uk
  53. Wilts, England | 70734.126@compuserve.com
  54. -----------------------------------------
  55.